import tkinter as tk  # 导入tkinter模块
from tkinter import messagebox
import pymysql

from 文件操作 import db
from 用户界面 import MainPage

DBHOST = 'localhost'
DBUSER = 'root'
PASSWORD = 'kongxingli2002'
DBNAME = 'supermarket'


class LoginPage:

    def __init__(self, master):
        self.root = master  # 窗口

        # 登录界面
        self.root.geometry('300x180')
        self.root.title('用户页面')

        # 用户块(必须在界面创建后)
        self.username = tk.StringVar()  # tk类型下的变量
        self.password = tk.StringVar()

        # 创建面纸
        self.page1 = tk.Frame(self.root)
        self.page1.pack()

        # 布局
        tk.Label(self.page1).grid(row=0, column=0)

        # 用户栏
        tk.Label(self.page1, text='用户名').grid(row=1, column=1)
        tk.Entry(self.page1, textvariable=self.username).grid(row=1, column=2,
                                                              pady=10)  # pady上下的间距,Entry输入栏，textvariable摄取变量

        # 密码栏
        tk.Label(self.page1, text='密码').grid(row=2, column=1)
        tk.Entry(self.page1, show='*', textvariable=self.password).grid(row=2, column=2)

        # 按钮
        tk.Button(self.page1, text='登录', command=self.login).grid(row=3, column=1, pady=30)
        tk.Button(self.page1, text='返回', command=self.page1.quit).grid(row=3, column=2)

    def login(self):
        name = self.username.get()
        pwd = self.password.get()
        print(name, pwd)

        # 检查输入
        if not name:
            messagebox.showinfo('提示', "用户名不能为空,请输入账号！")
            return
        if not pwd:
            messagebox.showinfo('提示', "密码不能为空,请输入密码！")
            return

        # 登录验证
        login_successful = self.login_verify(name, pwd)
        if login_successful:
            # 销毁界面,跳转界面
            self.page1.destroy()
            # 加载界面
            MainPage(self.root)
        else:
            messagebox.showinfo('提示', "用户名或密码错误，请重新输入！")
            self.password.set('')  # 清空密码输入框

    # 登录验证
    def login_verify(self, username, password):
        return self.login_db(username, password)

    # 连接数据库，验证
    def login_db(self, username, password):
        print("数据库验证:", username, password)
        try:
            # with 语句管理数据库连接,确保数据库关闭
            with pymysql.connect(host=DBHOST, user=DBUSER, password=PASSWORD, database=DBNAME) as conn:
                with conn.cursor() as cursor:
                    sql = 'SELECT * FROM USERS WHERE 账户名=%s AND 密码=%s'
                    cursor.execute(sql, (username, password))
                    result = cursor.fetchall()
                    conn.commit()
                    return len(result) > 0
        except pymysql.MySQLError as e:
            print("数据库连接错误:", e)
            messagebox.showerror('错误', '无法连接到数据库，请稍后再试。')
            return False


if __name__ == '__main__':
    root = tk.Tk()
    LoginPage(master=root)
    root.mainloop()